﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using SPC.Chart;
using SPC.Data;
using System.IO;
using SPCTest;
using System.Threading;

namespace SPC
{
    public partial class SpcAnalyzer : Form
    {
        SPControl spc;
        double[][] data=new double[0][];
        double[] xData=new double[0];//化为1维数据
        
        public SpcAnalyzer()
        {
            InitializeComponent();
        
        }

        private void BtnGetData_Click(object sender, EventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog();            
            fd.Filter = "Xbar-R files|*.xbr.xlsx;*.xbr.xls|Xbar-S files|*.xbs.xlsx;*.xbs.xls";
            fd.Filter += "|X-Rm files|*.xrm.xlsx;*.xrm.xls|P Chart files|*.p.xlsx;*.p.xls";
            fd.Filter += "|NP Chart files|*.np.xlsx;*.np.xls|C Chart files|*.c.xlsx;*.c.xls";
            fd.Filter += "|U Chart files|*.u.xlsx;*.u.xls|All Excel files|*.xlsx;*.xls;*.xlsb";
            if (fd.ShowDialog() == DialogResult.OK)
            {
                Text = "SPC Analysis " + fd.FileName;
                data = new double[0][];
                xData = new double[0];
                barChart1.GroupingPolicy = EGroupingPolicy.normal;
                XlsImport xls = new XlsImport();
                SSpcSpecs sspecs = xls.ReadSpcSpec(fd.FileName);
                txtLSL.Text = sspecs.lsl.ToString();
                txtUSL.Text = sspecs.usl.ToString();
                txtCpkLimit.Text = sspecs.cpkLimt.ToString();
                int digitals = 0;//小数点的位数

                if (fd.FilterIndex==1)//Xbar-R
                {
                    data = xls.ReadDataForXbar_R(fd.FileName);
                }
                else if(fd.FilterIndex==2)//Xbar-S
                {
                    data = xls.ReadDataForXbar_S(fd.FileName);
                }
                else if (fd.FilterIndex == 3)//X-Rm
                {
                    xData = xls.ReadDataForX_Rm(fd.FileName);
                }
                else if (fd.FilterIndex == 4)//P
                {
                    data = xls.ReadDataForPchart(fd.FileName);
                }
                else if (fd.FilterIndex == 5)//NP
                {
                    data = xls.ReadDataForNPchart(fd.FileName);
                }
                else if (fd.FilterIndex == 6)//C
                {
                    xData = xls.ReadDataForCchart(fd.FileName);
                }
                else if (fd.FilterIndex == 7)//U
                {
                    data = xls.ReadDataForUchart(fd.FileName);
                }
                dataGridView1.DataSource = xls.GetRawData();
                if(data.Length>0)
                {
                    
                    barChart1.SendData(data);
                    barChart1.RefreshChart();
                    for (int i = 0; i < data[0].Length; i++)
                    {
                        string s = data[0][i].ToString();
                        s = s.Substring(s.IndexOf('.') + 1);
                        int num = s.Length;
                        if (num > digitals) digitals = num;
                    }
                }
                else if(xData.Length>0)
                {
                   
                    barChart1.SendData(xData);
                    barChart1.RefreshChart();
                    for (int i = 0; i < xData.Length; i++)
                    {
                        string s = xData[i].ToString();
                        s = s.Substring(s.IndexOf('.') + 1);
                        int num = s.Length;
                        if (num > digitals) digitals = num;
                    }
                }
                lbDataType.Text = ((ECtrlChartType)fd.FilterIndex-1).ToString();
                ctrlChart1.Digitals = digitals;
                ChartIndexSeleted(fd.FilterIndex-1);

            }
        }

        private void chkUnormals_CheckedChanged(object sender, EventArgs e)
        {
            ctrlChart1.MarkUnormals = chkUnormals.Checked;
            List<SUnormals> unormaList = spc.GetUnormals();
            ctrlChart1.ShowUnormals(unormaList);
            if(chkUnormals.Checked)
            {
                if(unormaList.Count>0)//有异常点
                {
                    DialogResult ans= MessageBox.Show("有异常点发生，要查看详细信息吗？","提问",MessageBoxButtons.YesNo,MessageBoxIcon.Question);
                    if(ans==DialogResult.Yes)
                    {
                        EUnormals[] unormals = (from u in unormaList
                                                select u.UnNormType).Distinct().ToArray();
                        SaveFileDialog fd = new SaveFileDialog()
                        {
                            Filter = "Log files(*.log)|*.log|Text Files(*.txt)|*.txt|All Files|*.*",
                            FileName = "SPC Unormal.log"
                        };
                        if (fd.ShowDialog() == DialogResult.OK)
                        {
                            List<string> unMessageList = new List<string>();
                            int count = 0;
                            foreach (EUnormals u in unormals)
                            {
                                unMessageList.Add("异常" + count++);
                                unMessageList.Add(spc.GetUnormalMessege(u));
                            }
                            File.WriteAllLines(fd.FileName, unMessageList);
                            System.Diagnostics.Process.Start(fd.FileName);
                        }
                    }
                }
            }
        }

        private void chkAreaLines_CheckedChanged(object sender, EventArgs e)
        {
            ctrlChart1.EnableAreaLines = chkAreaLines.Checked;
        }

        private void cbChartType_SelectedIndexChanged(object sender, EventArgs e)
        {
            //ChartIndexSeleted(cbChartType.SelectedIndex);
        }
        private void ChartIndexSeleted(int chartTypeIndex)
        {
            ECtrlChartType chartType = (ECtrlChartType)chartTypeIndex;
            //不同控制图要求的数据格式不一样
            if (data.Length > 0)
            {
                spc = new SPControl(data, double.Parse(txtUSL.Text), double.Parse(txtLSL.Text), chartType);
            }
            else if (xData.Length > 0)
            {
                spc = new SPControl(xData, double.Parse(txtUSL.Text), double.Parse(txtLSL.Text), chartType);
            }
            SCtrlDiagram[] diag = spc.GetCtrlDiagrams();
            ctrlChart1.LoadDiagrams(diag);
            RefreshCPK();
        }
        private void RefreshCPK()
        {
            lbCP.Text = spc.CP().ToString("G3");
            lbCPK.Text = spc.CPK().ToString("G3");
            lbPP.Text = spc.PP().ToString("G3");
            lbPPK.Text = spc.PPK().ToString("G3");
        }
        private void txtLSL_Validated(object sender, EventArgs e)
        {
            if(spc!=null)  spc.LSL = double.Parse(txtLSL.Text);
        }

        private void txtUSL_Validated(object sender, EventArgs e)
        {
            if(spc!=null)  spc.USL = double.Parse(txtUSL.Text);
        }

        private void lbPP_TextChanged(object sender, EventArgs e)
        {
            if(spc.IsCpkPass())
            {
                lbCPK.BackColor = Color.FromKnownColor(KnownColor.Control);
            }
            else
            {
                lbCPK.BackColor = Color.Red;
            }
        }

        private void btnAbout_Click(object sender, EventArgs e)
        {
            
        }

        private void btnApply_Click(object sender, EventArgs e)
        {
            if(double.TryParse(txtCpkLimit.Text, out double cpklimit))
                spc.CPKLimit = cpklimit;
            if (double.TryParse(txtLSL.Text, out double lsl))
            {
                spc.LSL = lsl;
                RefreshCPK();
            }
                
            if (double.TryParse(txtUSL.Text, out double usl))
            {
                spc.USL = usl;
                RefreshCPK();
            }
                
        }

        private void sbtnHelp_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("SPCHelp.ppsx");
        }

        private void sbtnAbout_Click(object sender, EventArgs e)
        {
            AboutBox1 abox = new AboutBox1();
            abox.ShowDialog();
        }
    }
}
